import Modal from '@/components/Modal';
import { Form } from 'antd';
import { Component } from 'react';

export default class FormModal extends Component {
  modalRef = (modal) => {
    const { modalRef } = this.props;
    modalRef && modalRef(modal);
    this.modal = modal;
  };

  formRef = (form) => {
    const { formRef } = this.props;
    formRef && formRef(form);
  };

  handleOk = () => {
    const { onFinish } = this.props;
    return this.form.validateFields().then((values) => {
      if (onFinish) {
        return onFinish(values);
      }
    });
  };

  render() {
    const { children, initialValues, onFinish, modalRef, loading, ...props } =
      this.props;
    const formProps = { initialValues };

    return (
      <Modal onOk={this.handleOk} {...props} ref={this.modalRef}>
        {(info) => (
          <Form
            loading={loading || info.loading}
            {...formProps}
            ref={(form) => {
              this.form = form;
              this.formRef(form);
            }}
          >
            {children}
          </Form>
        )}
      </Modal>
    );
  }
}
